import axios from 'axios';
import config from './config';
import CryptoJS from 'crypto-js';

const PASSWORD_SECRET = 'password_secret_456';

const apiClient = axios.create({
  baseURL: config.API_BASE_URL,
  headers: { 'Content-Type': 'application/json' }
});

// **用户登录**
export const login = async (username, password) => {
  try {
    const encryptedPassword = CryptoJS.AES.encrypt(password, PASSWORD_SECRET).toString();

    const response = await apiClient.post('/login', {
      username,
      password: encryptedPassword
    });

    const token = response.headers['authorization'];
    const userId = response.data.userId; // 获取后端返回的用户ID
    // console.log(userId,'userId');

    if (token) {
      localStorage.setItem('token', token);
      localStorage.setItem('userId', userId); // 存储用户ID
    }

    return { success: true, userId };
  } catch (error) {
    console.error('Login API Error:', error);
    return { success: false, message: error.response?.data?.message || '登录失败' };
  }
};


// **用户注册**
export const register = async (username, email, password) => {
  try {
    const encryptedPassword = CryptoJS.AES.encrypt(password, PASSWORD_SECRET).toString();

    const response = await apiClient.post('/register', {
      username,
      email,
      password: password
    });

    return response.data; // { success: true, message: "注册成功" }
  } catch (error) {
    console.error('Register API Error:', error);
    return { success: false, message: error.response?.data?.message || '注册失败' };
  }
};

// **获取受保护数据**
export const getProtectedData = async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    return { success: false, message: '未登录' };
  }

  try {
    const response = await apiClient.get('/protected', {
      headers: { Authorization: `Bearer ${token}` }
    });
    return response.data;
  } catch (error) {
    console.error('Protected API Error:', error);
    return { success: false, message: error.response?.data?.message || '请求失败' };
  }
};

// **请求未学习过的单词 (Custom Limit)**
export const getUnlearnedWords = async (userId, limit) => {
  const token = localStorage.getItem('token');

  // If the token doesn't exist, return an error
  if (!token) {
    return { success: false, message: '未登录' };
  }

  // If the limit is not a number or is less than 1, set a default limit
  if (isNaN(limit) || limit < 1) {
    limit = 10; // Default to 10 if the limit is invalid
  }

  try {
    const response = await apiClient.post('/get-unlearned-words', {
      user_id: userId,
      limit: limit
    }, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return response.data; // Returns the list of unlearned words
  } catch (error) {
    console.error('Get Unlearned Words API Error:', error);
    return { success: false, message: error.response?.data?.message || '请求失败' };
  }
};

// **提交学习过的单词**
export const saveLearnedWords = async (userId, learnedWords) => {
  const token = localStorage.getItem('token');

  if (!token) {
    return { success: false, message: '未登录' };
  }

  if (!Array.isArray(learnedWords) || learnedWords.length === 0) {
    return { success: false, message: '学习记录不能为空' };
  }

  try {
    const response = await apiClient.post('/insert-user-words', {
      userId,
      learnedWords
    }, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return response.data; // { success: true, message: "学习记录插入成功" }
  } catch (error) {
    console.error('Save Learned Words API Error:', error);
    return { success: false, message: error.response?.data?.message || '提交学习记录失败' };
  }
};


// **查询用户学习统计信息**
export const getUserStats = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    // 发送 GET 请求获取学习统计信息
    const response = await apiClient.get(`/user-stats/${userId}`, {
      headers: { 'Authorization': `Bearer ${token}` } // 带上 token 进行身份验证
    });

    return { success: true, stats: response.data.stats };
  } catch (error) {
    console.error('Error fetching user stats:', error);
    return { success: false, message: error.response?.data?.message || '获取统计信息失败' };
  }
};


// **查询用户单词笔记**
export const getUserNotes = async (userId, wordId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    // 发送 GET 请求获取用户单词笔记
    const response = await apiClient.get(`/getNotes`, {
      params: { user_id: userId, word_id: wordId }, // 传递查询参数
      headers: { 'Authorization': `Bearer ${token}` } // 带上 token 进行身份验证
    });

    return { success: true, notes: response.data };
  } catch (error) {
    console.error('Error fetching user notes:', error);
    return { success: false, message: error.response?.data?.message || '获取单词笔记失败' };
  }
};

